#!/bin/bash
# EMS systemd 用户问题快速修复脚本

set -e

echo "========================================="
echo "  EMS systemd 用户问题修复"
echo "========================================="
echo

# 检查是否以 root 运行
if [ "$EUID" -ne 0 ]; then
    echo "错误: 请使用 sudo 运行"
    echo "示例: sudo ./fix-systemd-user.sh"
    exit 1
fi

PROJECT_ROOT="/home/sunfly/ems-cpp-v1"
UNIT_FILE="/etc/systemd/system/ems-dispatch.service"

# 检测正确的用户
echo "1. 检测运行用户..."
if id sunfly &>/dev/null; then
    RUN_USER="sunfly"
    RUN_GROUP="sunfly"
    echo "   ✓ 使用用户: sunfly"
elif id pi &>/dev/null; then
    RUN_USER="pi"
    RUN_GROUP="pi"
    echo "   ✓ 使用用户: pi"
else
    echo "   ✗ 未找到 sunfly 或 pi 用户"
    echo "   当前系统用户:"
    cut -d: -f1 /etc/passwd | grep -v "^_" | head -10
    exit 1
fi

# 修复项目目录权限
echo
echo "2. 修复项目目录权限..."
chown -R $RUN_USER:$RUN_GROUP "$PROJECT_ROOT"
echo "   ✓ 已设置 $PROJECT_ROOT 所有者为 $RUN_USER:$RUN_GROUP"

# 确保可执行文件有执行权限
echo
echo "3. 修复可执行文件权限..."
if [ -f "$PROJECT_ROOT/build/bin/ems-cpp-v1" ]; then
    chmod +x "$PROJECT_ROOT/build/bin/ems-cpp-v1"
    echo "   ✓ 已设置可执行权限"
else
    echo "   ✗ 可执行文件不存在: $PROJECT_ROOT/build/bin/ems-cpp-v1"
    echo "   请先编译项目:"
    echo "   cd $PROJECT_ROOT && mkdir -p build && cd build"
    echo "   cmake .. && cmake --build . -- -j4"
    exit 1
fi

# 更新 systemd 单元文件
echo
echo "4. 更新 systemd 单元文件..."
cat > "$UNIT_FILE" <<EOF
[Unit]
Description=EMS Energy Management System
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$RUN_USER
Group=$RUN_GROUP
WorkingDirectory=$PROJECT_ROOT
ExecStart=$PROJECT_ROOT/build/bin/ems-cpp-v1 --config $PROJECT_ROOT/config
Restart=always
RestartSec=5
StartLimitBurst=5
StartLimitIntervalSec=60
StandardOutput=journal
StandardError=journal
SyslogIdentifier=ems-dispatch

[Install]
WantedBy=multi-user.target
EOF
echo "   ✓ 单元文件已更新 (User=$RUN_USER)"

# 重新加载并重启
echo
echo "5. 重新加载 systemd..."
systemctl daemon-reload
echo "   ✓ systemd 已重新加载"

echo
echo "6. 重启服务..."
systemctl restart ems-dispatch.service
sleep 2

echo
echo "7. 检查服务状态..."
if systemctl is-active --quiet ems-dispatch.service; then
    echo "   ✓ 服务运行正常"
    systemctl status ems-dispatch.service --no-pager -l
else
    echo "   ✗ 服务仍未启动，查看详细日志:"
    journalctl -u ems-dispatch.service -n 50 --no-pager
    exit 1
fi

echo
echo "========================================="
echo "  修复完成!"
echo "========================================="
echo
echo "查看实时日志:"
echo "  sudo journalctl -u ems-dispatch.service -f"
echo
echo "测试 Web 访问:"
echo "  curl http://localhost:9527"
echo
